<template>
  <div>
    <!-- 头部 -->
    <div class="m-b-20 ovf-hd">
      <!-- 页面跳转 -->
      <div class="fl ">
        <el-button type="danger" icon="document">区县代理总数: {{data.received.count}}</el-button>
        <el-button type="primary" icon="document" @click="AddItems" v-if="!Add.disabled">新增区县代理</el-button>
        <!-- <el-button type="primary" icon="document" @click="toItems" v-if="!Others.disabled">转让</el-button> -->
      </div>
      <!-- 导出Excel表格 -->
      <downExcel :baseApi="config.baseApi" :config="config.excel" :tableData="data.received.table" :conditions="data.exchanged.search"></downExcel>
      <div>
        <!-- 搜索 -->
        <search-model :config="config.search" :data="data"></search-model>
      </div>
    </div>
    <!-- 头部 -->

    <!-- 内容 -->
    <transition name="fade" mode="out-in" appear>
      <table-model v-loading="showLoading" :Edit="Edit" :tableData="data.received.table" :config="config.table" :exchanged="data.exchanged" :baseApi="config.baseApi"></table-model>
    </transition>
    <!-- 内容 -->

    <!-- 底部 -->
    <div class="pos-rel p-t-20">
      <!-- 批量操作 -->
      <btnGroup v-if="!config.table.noGroup" :selectedData="data.exchanged.multipleSelection" :baseApi="config.baseApi" :config="config.table.btnGroup" :exchanged="data.exchange"></btnGroup>
      <!-- 翻页操作 -->
      <page-model :data="data" :config="config.page" :dataCount="data.received.count" :limit="data.exchanged.search.limit" :currentPage="data.exchanged.search.page"></page-model>
    </div>
    <!--底部 -->
    <!-- 新增 -->
    <el-dialog :title="Add.config.title" :visible.sync="Add.dialogFormVisible">
      <el-form ref="form" :model="Add.data.form" :rules="Add.config.rules" label-width="130px">

        <!-- 普通输入类型 -->
        <el-form-item :label="item.label" :prop="item.prop" v-for="item in Add.config.form.input">
          <el-input v-model.trim="Add.data.form[item.prop]" class="h-40 w-200" :maxlength="255"></el-input>
        </el-form-item>

        <el-form-item v-if="realName">
          推荐人姓名: {{realName}}
        </el-form-item>

        <el-form-item :label="item.label" :prop="item.prop" v-for="item in Add.config.form.select">
          <el-select filterable v-model="Add.data.form[item.prop]" :placeholder="item.placeholder" class="w-200">
            <el-option v-for="option in Add.data.selectData[item.prop]" :label="option.label" :value="option.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label="item.label" :prop="item.prop" v-for="item in Add.config.form.multipleSelect">
          <el-select filterable v-model="Add.data.form[item.prop]" :placeholder="item.placeholder" class="w-200" multiple>
            <el-option v-for="option in Add.data.selectData[item.prop]" :label="option.label" :value="option.value"></el-option>
          </el-select>
        </el-form-item>

        <!-- 图片上传 -->
        <el-form-item :label="this.Add.config.form.uploadImg.label" v-if="this.Add.config.form.uploadImg.label">
          <el-upload class="avatar-uploader" :action="Add.config.uploadUrl" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="Add.data.form[this.Add.config.form.uploadImg.prop]" :src="Add.config.domain + Add.data.form[this.Add.config.form.uploadImg.prop]" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="Add.dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="commitAdd">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 新增 -->

    <!-- 转让 -->
    <el-dialog :title="Others.config.title" :visible.sync="Others.dialogFormVisible">
      <el-form ref="form" :model="Others.data.form" :rules="Others.config.rules" label-width="130px">

        <!-- 普通输入类型 -->
        <el-form-item :label="item.label" :prop="item.prop" v-for="item in Others.config.form.input">
          <el-input v-model.trim="Others.data.form[item.prop]" class="h-40 w-200" :maxlength="255"></el-input>
        </el-form-item>

        <el-form-item :label="item.label" :prop="item.prop" v-for="item in Others.config.form.select">
          <el-select filterable v-model="Others.data.form[item.prop]" filterable :placeholder="item.placeholder" class="w-200">
            <el-option v-for="option in Others.data.selectData[item.prop]" :label="option.label" :value="option.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label="item.label" :prop="item.prop" v-for="item in Others.config.form.multipleSelect">
          <el-select filterable v-model="Others.data.form[item.prop]" filterable :placeholder="item.placeholder" class="w-200" multiple>
            <el-option v-for="option in Others.data.selectData[item.prop]" :label="option.label" :value="option.value"></el-option>
          </el-select>
        </el-form-item>

        <!-- 图片上传 -->
        <el-form-item :label="this.Others.config.form.uploadImg.label" v-if="this.Others.config.form.uploadImg.label">
          <el-upload class="avatar-uploader" :action="Others.config.uploadUrl" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="Others.data.form[this.Others.config.form.uploadImg.prop]" :src="Others.config.domain + Others.data.form[this.Others.config.form.uploadImg.prop]" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="Others.dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="commitOthers">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 转让 -->

  </div>
</template>

<script>
import http from "assets/js/http.js";
import btnGroup from "components/Common/btn-group-nodelete.vue";
import downExcel from "components/Common/down-excel-dsmange.vue";
import tableModel from "components/Common/table-model-address.vue";
import searchModel from "components/Common/search-model.vue";
import pageModel from "components/Common/page-model.vue";
import cities from "assets/data/address.json";

export default {
  components: {
    btnGroup,
    downExcel,
    tableModel,
    searchModel,
    pageModel
  },
  data() {
    return {
      realName: null,
      Others: {
        dialogFormVisible: false,
        data: {
          primary: "",
          form: {
            username: null,
            giveMoney: null,
            remark: null,
            type: null
          },
          selectData: {
            type: [
              { label: "赠送医养储备金", value: 1 },
              { label: "可用医养储备金", value: 2 },
              { label: "现金", value: 3 }
            ]
          }
        },
        config: {
          uploadUrl: "axios.defaults.baseUR + 'admin/upload'",
          domain: "axios.defaults.baseUR",
          title: "转让储备金",
          form: {
            input: [
              { prop: "username", label: "转让账户名" },
              { prop: "giveMoney", label: "转让金额" },
              { prop: "remark", label: "备注" }
            ],
            select: [{ prop: "type", label: "类型" }],
            uploadImg: []
          },
          rules: {
            bankNumber: [{ required: true, message: "请输入银行卡号" }],
            shopName: [{ required: true, message: "请输入" }],
            referName: [{ required: true, message: "请输入推荐人账户" }],
            province: [{ required: true, message: "请输入省" }],
            city: [{ required: true, message: "请输入市" }],
            hometown: [{ required: true, message: "请输入区" }],
            bankName: [{ required: true, message: "请输入" }],
            bankAddress: [{ required: true, message: "请输入" }],
            cardholder: [{ required: true, message: "请输入持卡人" }],
            governor: [{ required: true, message: "请输入省代" }],
            mayor: [{ required: true, message: "请输入市代" }]
          }
        }
      },
      Add: {
        dialogFormVisible: false,
        data: {
          primary: "",
          form: {
            username: null,
            cellphone: null,
            referUsername: null,
            password: null,
            paypass: null,
            roleId: 5,
            joinMoney: 300000,
            province: null,
            city: null,
            hometown: null
          },
          selectData: {
            province: [],
            city: [],
            hometown: []
          }
        },
        config: {
          uploadUrl: "axios.defaults.baseUR + 'admin/upload'",
          domain: "axios.defaults.baseUR",
          title: "新增区县代理",
          form: {
            input: [
              { prop: "username", label: "账户名" },
              { prop: "realName", label: "姓名" },
              { prop: "cellphone", label: "联系方式" },
              { prop: "joinMoney", label: "加盟费" },
              { prop: "referUsername", label: "推荐人账户" }
            ],
            select: [
              { prop: "province", label: "区县代所属省" },
              { prop: "city", label: "区县代所属市" },
              { prop: "hometown", label: "区县代所属区县" }
            ],
            uploadImg: []
          },
          rules: {
            username: [{ required: true, message: "请输入账户名" }],
            realName: [{ required: true, message: "请输入姓名" }],
            joinMoney: [{ required: true, message: "请输入加盟费" }],
            cellphone: [{ required: true, message: "请输入联系方式" }],
            province: [{ required: true, message: "请输入所属省" }],
            city: [{ required: true, message: "请输入所属市" }],
            hometown: [{ required: true, message: "请输入所属区县" }]
          }
        }
      },
      Edit: {
        dialogFormVisible: false,
        data: {
          primary: "",
          form: {
            balance: null,
            emoney: null,
            level: null,
            cellphone: null,
            referUsername: null,
            password: null,
            paypassForModify: null,
            bankNumber: null,
            bankAddress: null,
            cardholder: null,
            province: "",
            city: "",
            hometown: ""
          },
          selectData: {
            level: [
              { label: "非董事", value: 0 },
              { label: "一级董事", value: 1 },
              { label: "二级董事", value: 2 },
              { label: "三级董事", value: 3 },
              { label: "四级董事", value: 4 },
              { label: "五级董事", value: 5 },
              { label: "六级董事", value: 6 },
              { label: "七级董事", value: 7 }
            ],
            province: [],
            city: [],
            hometown: []
          }
        },
        config: {
          uploadUrl: axios.defaults.baseURL + "admin/upload",
          domain: axios.defaults.baseURL,
          title: "编辑区县信息",
          form: {
            input: [
              { prop: "remark", label: "本次修改备注" },
              { prop: "realName", label: "姓名" },
              { prop: "cellphone", label: "手机号" },
              { prop: "balance", label: "现金账户" },
              { prop: "password", label: "登录密码" },
              { prop: "paypassForModify", label: "支付密码" },
              { prop: "referShopNum", label: "推荐数量" }
            ],
            select: [{ prop: "level", label: "董事级别" }],
            uploadImg: []
          },
          rules: {
            remark: [{ required: true, message: "请输入本次修改的备注信息" }]
          }
        }
      },
      config: {
        baseApi: "pudu/members",
        excel: {
          fileName: "区列表",
          tHeader: [
            "用户名",
            "手机号",
            "账户余额",
            "推荐人",
            "董事级别",
            "省",
            "市",
            "区",
            "注册时间"
          ],
          filterVal: [
            "username",
            "cellphone",
            "balance",
            "referUsername",
            "levelTitle",
            "province",
            "city",
            "hometown",
            "createDate"
          ]
        },
        table: {
          noGroup: false,
          checkbox: true,
          status: true,
          sort: { createDate: "custom" },
          show: {
            items: [
              "用户名",
              "手机号",
              "账户余额",
              "推荐人",
              "董事级别",
              "省",
              "市",
              "区",
              "注册时间"
            ],
            prop: [
              "username",
              "cellphone",
              "balance",
              "referUsername",
              "levelTitle",
              "province",
              "city",
              "hometown",
              "createDate"
            ],
            width: [80, 110, 100, 80, 100, 80, 80, 80, 160, 60, 60]
          },
          operate: {
            del: false,
            edit: true
          }
        },
        search: {
          search_input: [
            { name: "username", placeholder: "用户名" },
            { name: "cellPhone", placeholder: "手机号" },
            { name: "balance", placeholder: "账户余额" },
            { name: "referName", placeholder: "推荐人" }
          ],
          search_select: [
            { name: "province", placeholder: "省" },
            { name: "city", placeholder: "市" },
            { name: "hometown", placeholder: "区" },
            { name: "status", placeholder: "状态" }
          ],
          date: [
            {
              name: "createDate",
              placeholder: "日期",
              type: "datetimerange",
              separator: "--",
              size: "large"
            }
          ]
        },
        page: {
          limits: [5, 10, 20, 50, 100],
          layout: "total, sizes, prev, pager, next, jumper"
        }
      },
      data: {
        received: {
          table: [],
          count: null,
          search: {
            status: [
              { label: "启用", value: "1" },
              { label: "禁用", value: "0" }
            ],
            level: [
              { label: "非懂事", value: 0 },
              { label: "一级懂事", value: 1 },
              { label: "二级懂事", value: 2 },
              { label: "三级懂事", value: 3 },
              { label: "四级懂事", value: 4 },
              { label: "五级懂事", value: 5 },
              { label: "六级懂事", value: 6 },
              { label: "七级懂事", value: 7 }
            ],
            province: [],
            city: [],
            hometown:[],
            cityId: null,
            regionId: null
          }
        },
        exchanged: {
          search: {
            limit: 5,
            page: 1,
            orderByString: "createDate.descending",
            roleId: 5,
            createDate: "",
            province: "",
            city:""
          },
          date: { createDate: "" },
          multipleSelection: [],
          isDelete: 0
        }
      }
    };
  },
  created() {
    for (let i in cities) {
      this.data.received.search.province.push({ level: i, value: i });
    }
   
    //搜索处监听省
    this.$watch("data.exchanged.search.province", {
      deep: true,
      handler: function(nowValue) {
        for (let i in cities[nowValue]) {
          this.data.received.search.city.push({ level: i, value: i });
        }
      }
    });
    //搜索处监听市
    this.$watch("data.exchanged.search.city", {
      deep: true,
      handler: function(nowValue) {
        cities[this.data.exchanged.search.province][nowValue].map(item=>{
          this.data.received.search.hometown.push({ level: item, value: item });
        }) 
      }
    });
    this.init();
    // 延迟绑定监听
    this.$watch("data.exchanged.search", {
      deep: true,
      handler: function(value) {
        router.push({ path: this.$route.path, query: this.getCondition() });
        _g.openGlobalLoading();
        this.tableData();
      }
    });
    this.$watch("data.exchanged.isDelete", {
      deep: true,
      handler: function() {
        _g.openGlobalLoading();
        this.tableData();
      }
    });

    // 监听省
    this.$watch("Add.data.form.province", {
      deep: true,
      handler: function() {
        this.getCity();
      }
    });
    // 监听市
    this.$watch("Add.data.form.city", {
      deep: true,
      handler: function() {
        this.getHomwtown();
      }
    });
    // 监听推荐人
    this.$watch("Add.data.form.referUsername", {
      deep: true,
      handler: function() {
        this.getreferRealName();
      }
    });
  },
  methods: {
    getreferRealName() {
      let url = "Pudu/Members/ForRealName";
      const data = {
        params: {
          username: this.Add.data.form.referUsername
        }
      };
      this.apiGet(url, data).then(res => {
        this.handelResponse(res, data => {
          this.realName = data;
        });
      });
    },
    getSelect() {
      let tmp = {};
      // 获取省的数据
      for (let i in cities) {
        tmp.label = i;
        tmp.value = i;
        this.Add.data.selectData.province[
          this.Add.data.selectData.province.length
        ] = JSON.parse(JSON.stringify(tmp));
      }
    },
    init() {
      // 基本数据获取
      this.tableData();
      this.getCityId();
      this.getRegionId();
      this.getSelect();
    },
    AddItems() {
      this.Add.dialogFormVisible = true; // 显示窗体
    },
    toItems() {
      this.Others.dialogFormVisible = true; // 显示窗体
    },
    getCityId() {
      let url = "pudu/members?roleId=3&limit=-1";
      this.apiGet(url).then(res => {
        this.handelResponse(res, data => {
          data.list.map(function(i) {
            i.value = i.id;
            i.label = i.username;
          });
          this.Edit.data.selectData.cityId = data.list;
          this.data.received.search.cityId = data.list;
          this.Add.data.selectData.cityId = data.list;
        });
      });
    },
    getRegionId() {
      let url = "pudu/members?roleId=5&limit=-1";
      this.apiGet(url).then(res => {
        this.handelResponse(res, data => {
          data.list.map(function(i) {
            i.value = i.id;
            i.label = i.username;
          });
          this.data.received.search.regionId = data.list;
          this.Edit.data.selectData.regionId = data.list;
          this.Add.data.selectData.regionId = data.list;
        });
      });
    },
    getCity() {
      // TODO 清除已有的市信息
      this.Add.data.form.city = "";
      this.Add.data.selectData.city = [];
      let tmp = {};
      // 获取省的数据
      for (let i in cities[this.Add.data.form.province]) {
        tmp.label = i;
        tmp.value = i;
        this.Add.data.selectData.city[
          this.Add.data.selectData.city.length
        ] = JSON.parse(JSON.stringify(tmp));
      }
    },
    getHomwtown() {
      // TODO 清除已有的市信息
      this.Add.data.form.hometown = "";
      this.Add.data.selectData.hometown = [];
      console.log(cities[this.Add.data.form.province][this.Add.data.form.city]);
      let tmp = {};
      // 获取省的数据
      for (let i in cities[this.Add.data.form.province][
        this.Add.data.form.city
      ]) {
        tmp.label =
          cities[this.Add.data.form.province][this.Add.data.form.city][i];
        tmp.value =
          cities[this.Add.data.form.province][this.Add.data.form.city][i];
        this.Add.data.selectData.hometown[
          this.Add.data.selectData.hometown.length
        ] = JSON.parse(JSON.stringify(tmp));
      }
    },
    tableData() {
      // 表格数据
      const data = {
        params: this.getCondition()
      };
      // 请求地址
      let url = this.config.baseApi;
      this.apiGet(url, data).then(res => {
        this.handelResponse(res, data => {
          data.list.map(function(i) {
            if (i.level == 0) {
              i.levelTitle = "非董事";
            }
            if (i.level == 1) {
              i.levelTitle = "一级董事";
            }
            if (i.level == 2) {
              i.levelTitle = "二级董事";
            }
            if (i.level == 3) {
              i.levelTitle = "三级董事";
            }
            if (i.level == 4) {
              i.levelTitle = "四级董事";
            }
            if (i.level == 5) {
              i.levelTitle = "五级董事";
            }
            if (i.level == 6) {
              i.levelTitle = "六级董事";
            }
            if (i.level == 7) {
              i.levelTitle = "七级董事";
            }
          });

          this.data.received.table = data.list;
          this.data.received.count = data.dataCount;

          _g.closeGlobalLoading();
        });
      });
    },
    getCondition() {
      // 搜索优化配置
      let temp = this.data.exchanged.search;
      let params = {};
      for (let key in temp) {
        if (temp[key]) {
          params[key] = temp[key];
        }
      }
      return params;
    },
    commitAdd() {
      console.log(this.Add.data.form);
      this.$refs.form.validate(pass => {
        if (pass) {
          // 提交数据
          this.apiPost(this.config.baseApi, this.Add.data.form).then(res => {
            this.handelResponse(
              res,
              data => {
                _g.toastMsg("success", "新增成功!");
                this.data.exchanged.isDelete++;
                this.Add.dialogFormVisible = false; // 显示窗体
              },
              () => {
                this.isLoading = !this.isLoading;
              }
            );
          });
        }
      });
    },
    commitOthers() {
      console.log(this.Others.data.form);
      this.$refs.form.validate(pass => {
        if (pass) {
          // 提交数据
          let url = "pudu/giveMoney";
          this.apiPost(url, this.Others.data.form).then(res => {
            this.handelResponse(
              res,
              data => {
                _g.toastMsg("success", "转让成功!");
                this.data.exchanged.isDelete++;
                this.Others.dialogFormVisible = false; // 显示窗体
              },
              () => {
                this.isLoading = !this.isLoading;
              }
            );
          });
        }
      });
    },
    handleAvatarSuccess(res, file) {
      this.Add.data.form[this.Add.config.form.uploadImg.prop] = res.data;
      // this.imageUrl =
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isLt2M;
    }
  },
  mixins: [http]
};
</script>

<style scoped>
.el-input,
.el-input__inner {
  width: auto;
}
</style>
